package com.fy.fyspace.common.auth;

import cn.dev33.satoken.stp.StpInterface;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.fy.fyspace.constant.KeysConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 自定义权限加载接口实现类
 */
@Slf4j
@Component
public class StpInterfaceImpl implements StpInterface {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 返回一个账号所拥有的权限码集合
     */
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        List<String> permissionIdList = new ArrayList<>();

        if (!StpKit.SPACE.loginType.equals(loginType)) {
            log.info("当前权限体系不是space空间类型，无法获取对应权限列表");
            return permissionIdList;
        }
        Long userId = Long.valueOf(loginId.toString());

        // 获取权限JSON字符串
        String permissionJson = (String) redisTemplate.opsForValue()
                .get(KeysConstant.SPACE_PERMISSION_REDIS_KEY + userId);
        
        if (permissionJson == null || permissionJson.isEmpty()) {
            log.info("未找到任何权限配置");
            return permissionIdList;
        }

        // 解析JSON字符串为List<String>
        try {
            permissionIdList = JSON.parseObject(permissionJson, new TypeReference<List<String>>() {});
        } catch (Exception e) {
            log.error("解析权限JSON数据失败: {}", e.getMessage());
        }

        log.info("获取到的权限id列表:{}", permissionIdList);
        return permissionIdList;
    }

    /**
     * 返回一个账号所拥有的角色优先级值
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        List<String> roleList = new ArrayList<>();

        if (!StpKit.SPACE.loginType.equals(loginType)) {
            log.info("当前权限体系不是space空间类型，无法获取对应角色列表");
            return roleList;
        }

        // 根据StpKit.SPACE.login(userId);获取登录用户id
        Object loginIdObj = StpKit.SPACE.getLoginId();
        if (loginIdObj == null || !loginIdObj.toString().equals(loginId.toString())) {
            log.info("用户未登录，无法获取角色列表");
            return roleList;
        }

        Long userId = Long.valueOf(loginId.toString());

        // 获取角色JSON字符串
        String roleJson = (String) redisTemplate.opsForValue()
                .get(KeysConstant.SPACE_ROLE_REDIS_KEY + userId);

        if (roleJson != null && !roleJson.isEmpty()) {
            try {
                roleList = JSON.parseObject(roleJson, new TypeReference<List<String>>() {});
            } catch (Exception e) {
                log.error("解析角色JSON数据失败: {}", e.getMessage());
            }
        }

        log.debug("用户{}的角色ID: {}", userId, roleList);
        return roleList;
    }
}
